package synchronicity.calendar;

import java.util.Enumeration;

import javax.microedition.pim.Event;
import javax.microedition.pim.EventList;
import javax.microedition.pim.PIM;
import javax.microedition.pim.PIMException;
import javax.microedition.pim.PIMItem;

import synchronicity.util.Range;
import synchronicity.util.RangeSet;

/**
 * A {@link PIM} implementation of a Calendar
 */
public class PIMCalendar implements Calendar {

	private static PIMCalendar instance;

	private PIMCalendar() {
	}

	public static synchronized PIMCalendar getInstance() {
		if (instance == null)
			instance = new PIMCalendar();
		return instance;
	}

	public RangeSet getBusyTimes(Range dateRange) {
		RangeSet result = new RangeSet();
		PIM pim = PIM.getInstance();
		try {
			EventList eventList = (EventList) pim.openPIMList(PIM.EVENT_LIST,
					PIM.READ_ONLY);
			Enumeration events = eventList.items(EventList.OCCURRING, dateRange
					.getLeft(), dateRange.getRight(), false);

			while (events.hasMoreElements()) {
				Event event = (Event) events.nextElement();
				result.addRange(event.getDate(Event.START, PIMItem.ATTR_NONE),
						event.getDate(Event.END, PIMItem.ATTR_NONE));
			}
		} catch (PIMException e) {
			e.printStackTrace();
		}
		return result;
	}

	public void addCalendarItem(Range dateRange, String title) throws ModifyCalendarFailedException {
		PIM pim = PIM.getInstance();
		try {
			EventList eventList = (EventList) pim.openPIMList(PIM.EVENT_LIST,
					PIM.READ_WRITE);
			Event event = eventList.createEvent();
			 if (eventList.isSupportedField(Event.SUMMARY))
			      event.addString(Event.SUMMARY, PIMItem.ATTR_NONE, title);
			 if (eventList.isSupportedField(Event.START))
			      event.addDate(Event.START, PIMItem.ATTR_NONE, dateRange.getLeft() );
			 if (eventList.isSupportedField(Event.END))
			      event.addDate(Event.END, PIMItem.ATTR_NONE, dateRange.getRight() );
			event.commit();
		} catch (PIMException e) {
			e.printStackTrace();
			throw new ModifyCalendarFailedException();
		}
	}
}
